package com.hm.cms.websit;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hm.cms.def.YibaiTypeEnum;
import com.hm.cms.service.ArticleService;
import com.hm.cms.service.TermsService;
import com.hm.cms.util.WebSitUtil;
import com.hm.cms.vo.HcmsArticleVo;
import com.hm.cms.vo.HcmsTermsVo;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.StringUtil;
import com.hm.common.util.WebUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 下午5:37:13 2017年11月14日
 * @version 1.0
 * @describe 
 */
@Slf4j
@Component
public class YibaiHandler {

	@Autowired
	private TermsService termsService;

	@Autowired
	private ArticleService articleService;

	public void handler(){
		for (YibaiTypeEnum enums:YibaiTypeEnum.values()){
			loadMainDirectory(enums.getType(),"1",enums.getTermTaxonomy());
			WebSitUtil.wating3();
		}
	}

	private void loadMainDirectory(String uri, String operationUserId, String tagId){
		try{
			Document document = Jsoup.connect(uri).get();
			Elements elements = document.getElementById("toptype-list").getElementsByTag("a");
			for(Element element:elements){
				String path = element.attr("href");
				if(!path.startsWith("http:")){
					continue;
				}
				loadMainArticle(path,operationUserId,tagId);
				WebSitUtil.wating3();
			}
		}catch (Exception e){
			log.error(e.getMessage(),e);
		}
	}

	private void loadMainArticle(String uri, String operationUserId, String tagId) throws Exception{
		System.out.println("2----->"+uri);
		loadArticle(uri,operationUserId,tagId);
		loadDirectory(uri,operationUserId,tagId);
	}

	private void loadDirectory(String uri,String operationUserId, String tagId) throws Exception{
		try{
			Document document = Jsoup.connect(uri).get();
			Elements elements = document.getElementsByClass("pagemenu").get(0).getElementsByTag("a");
			for(Element element:elements){
				String path = element.attr("href");
				if(!path.startsWith("http:")){
					continue;
				}
				loadArticle(path,operationUserId,tagId);
			}
		}catch (Exception e){
			log.error(e.getMessage(),e);
		}
	}

	private void loadArticle(String uri,String operationUserId, String tagId) throws Exception{
		try{
			System.out.println("3----->"+uri);
			if (articleService.checkArticleSourceUri(uri)) {
				return;
			}

			Document document = Jsoup.connect(uri).get();
			String description = document.select("meta[name=description]").get(0).attr("content");
			String keyStr = document.select("meta[name=keywords]").get(0).attr("content");
			List<String> termIds = new ArrayList<String>();
			String[] keys = keyStr.split(",");
			for (String key : keys) {
				if(CommonUtil.isEmpty(key)) {
					continue;
				}
				HcmsTermsVo hcmsTermsVo = termsService.getHcmsTermsByTermName(key);
				if (CommonUtil.isNotEmpty(hcmsTermsVo)) {
					termIds.add(hcmsTermsVo.getId());
					continue;
				}

				HcmsTermsVo termsVo = new HcmsTermsVo();
				termsVo.setTermName(key);
				termsVo.setTermCode(key);
				termsVo.setTermOrder(-1);
				termIds.add(termsService.addTerms(termsVo, operationUserId));
			}

			System.out.println("5--->");
			String title = document.getElementsByClass("article-title").get(0).html();
			Element element = document.getElementsByClass("article-content").get(0);
			element.getElementsByTag("blockquote").remove();
			element.getElementsByTag("em").remove();
            element.getElementsByTag("table").remove();
			element.getElementsByTag("input").remove();
            element.getElementsByTag("script").remove();
            element.getElementsByTag("div").remove();

            String content = element.html();
            
            System.out.println(content);
            
            if(StringUtil.isBlankOrNull(description)) {
            	description = StringUtil.dislodgeAllBlank(WebUtil.clearHtmlTags(content)).substring(0, 150);
            }
            
			HcmsArticleVo articleVo = new HcmsArticleVo();
			{
				articleVo.setTermIds(termIds);
				articleVo.setTermTayIds(Arrays.asList(tagId));
				articleVo.setArticleContent("<div class='row'>"+content.split("<br")[0]+"</div>");
				articleVo.setAuthorName("JoinTom");
				articleVo.setReleaseTime(System.currentTimeMillis());
				articleVo.setTitle(title);
				articleVo.setKeywords(StringUtil.isBlankOrNull(keyStr)?title:keyStr);
				articleVo.setSourceName("易百教育");
				articleVo.setSourceUri(uri);
				articleVo.setArticleOrder((int) articleService.getArtilcleMaxOrder());
				articleVo.setArticleExcerpt(description);
			}
			articleService.addArticle(articleVo, operationUserId);
		}catch (Exception e){
            System.out.println(uri);
            log.error(e.getMessage(),e);
		}
	}

	public static void main(String[] args) throws Exception{
        String uri = "http://www.yiibai.com/ant/ant_environment.html";
        Document document = Jsoup.connect(uri).get();

        String description = document.select("meta[name=description]").get(0).attr("content");
        System.out.println(description);
        String keyStr = document.select("meta[name=keywords]").get(0).attr("content");
        System.out.println(keyStr);

        System.out.println(document.getElementsByClass("article-title").get(0).html());


        Element element = document.getElementsByClass("article-content").get(0);
        element.getElementsByTag("blockquote").remove();
        element.getElementsByTag("em").remove();
        element.getElementsByTag("input").remove();
        element.getElementsByTag("script").remove();
        element.getElementsByTag("div").remove();

        String content = element.html();
        System.out.println(content.split("<br")[0]);
	}
}
